<template>
    <div class="organization-container content-wrapper">
        <el-row :gutter="20">

            <el-col :md="6" :lg="6">
            <div class="tree-header">
                <span>组织机构</span>
            </div>
            <el-tree :data="data" node-key="id" ref="tree"
                     v-loading="loading"
                     highlight-current
                     :check-strictly="true"
                     :default-expanded-keys="expandedKey"
                     :props="defaultProps"
                     @node-click="handleNodeClick"
            ></el-tree>
        </el-col>

            <el-col :md="18" :lg="18">
                <el-row>
                    <el-col :span="24">
                        <div class="detail-content">
                            <div class="wrapper">
                                <el-button type="primary" @click="handleCreate()">创建</el-button>
                                <el-button type="primary" @click="handleUpdate(detail)">编辑</el-button>
                                <el-button type="danger" @click="handleDelete(detail)">删除</el-button>
                                <el-button type="success" @click="handleReload">刷新</el-button>
                            </div>
                            <table>
                                <tr>
                                    <td>所属上级：</td>
                                    <td>{{detail.parentName == null ? '无上级' : detail.parentName}}</td>
                                </tr>
                                <tr>
                                    <td>机构名称：</td>
                                    <td>{{detail.name}}</td>
                                </tr>
                                <tr>
                                    <td>唯一标识：</td>
                                    <td>{{detail.identity}}</td>
                                </tr>
                                <tr>
                                    <td>备注：</td>
                                    <td>{{detail.remarks}}</td>
                                </tr>
                            </table>
                        </div>
                    </el-col>

                </el-row>

                <el-row class="margin-top-10">
                    <el-col :span="24">
                        <el-form :model="listQueryUser" :inline="true" ref="filterFormUser" style="display: inline-block">
                            <el-form-item prop="account" class="filter-item">
                                <el-input v-model="listQueryUser.account" placeholder="账号" style="width: 150px;"></el-input>
                            </el-form-item>
                            <el-form-item prop="realName" class="filter-item">
                                <el-input v-model="listQueryUser.realName" placeholder="姓名" style="width: 150px;"></el-input>
                            </el-form-item>
                            <el-form-item prop="sex" class="filter-item">
                                <el-select v-model="listQueryUser.sex" placeholder="性别" clearable style="width: 100px">
                                    <el-option
                                            v-for="item in sexOptions"
                                            :key="item.key"
                                            :label="item.label"
                                            :value="item.key">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="status" class="filter-item">
                                <el-select v-model="listQueryUser.status" placeholder="状态" style="width: 100px">
                                    <el-option
                                            v-for="item in statusOptions"
                                            :key="item.key"
                                            :label="item.label"
                                            :value="item.key">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="orderby" class="filter-item">
                                <el-select v-model="listQueryUser.orderby" placeholder="排序" style="width: 150px">
                                    <el-option
                                            v-for="item in sortOptions"
                                            :key="item.key"
                                            :label="item.label"
                                            :value="item.key">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-button class="filter-item" type="primary" icon="search" @click="handleFilterUser">搜索</el-button>
                            <el-button class="filter-item" type="primary" icon="mars-reset" @click="handleResetFilterUser">重置</el-button>
                        </el-form>

                        <el-table :data="listUser"
                                  v-loading="listLoadingUser"
                                  element-loading-text="给我一点时间"
                                  border
                                  fit
                                  highlight-current-row
                                  @selection-change="handleSelectionChangeUser"
                                  style="width: 100%">

                            <el-table-column
                                    type="selection"
                                    width="55">
                            </el-table-column>

                            <el-table-column label="序号" width="65" align="center">
                                <template slot-scope="scope"> {{scope.row.id}} </template>
                            </el-table-column>

                            <el-table-column label="姓名" width="110px" align="center">
                                <template slot-scope="scope"> {{scope.row.realName}} </template>
                            </el-table-column>

                            <el-table-column label="性别" width="80px" align="center">
                                <template slot-scope="scope"> {{scope.row.sex | sexFilter}} </template>
                            </el-table-column>

                            <el-table-column label="账号" width="110px" align="center">
                                <template slot-scope="scope"> {{scope.row.account}} </template>
                            </el-table-column>

                            <el-table-column label="手机号码" width="130px" align="center">
                                <template slot-scope="scope"> {{scope.row.mobile}} </template>
                            </el-table-column>

                            <el-table-column label="邮件地址" min-width="200px" align="center" show-overflow-tooltip>
                                <template slot-scope="scope"> {{scope.row.email}} </template>
                            </el-table-column>

                            <el-table-column label="操作" fixed="right" width="180px" align="center">
                                <template slot-scope="scope">
                                    <el-button size="small" type="danger" icon="delete" @click="handleDeleteUser(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>

                        </el-table>

                        <div v-show="!listLoadingUser" class="pagination-container">
                            <el-pagination
                                    @size-change="handleSizeChangeUser"
                                    @current-change="handleCurrentChangeUser"
                                    :current-page="listQueryUser.page"
                                    :page-sizes="[10, 20, 30, 50]"
                                    :page-size="listQueryUser.rows"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="totalUser">
                            </el-pagination>
                        </div>
                    </el-col>
                </el-row>
            </el-col>

        </el-row>
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleCloseDialog" size="small">

            <el-row>
                <el-col :md="6" :lg="6">
                    <el-tree :data="data" node-key="id"
                             highlight-current
                             :default-expanded-keys="expandedKeyEdit"
                             :props="defaultProps"
                             @node-click="handleSetParent"></el-tree>
                </el-col>
                <el-col :md="6" :lg="6">
                    <el-form :model="form" ref="form" labelPosition="right" labelWidth="80px" style="width: 400px">
                        <el-form-item label="所属上级" >
                            <el-input v-model="form.parentName" placeholder="请选择所属上级" readonly icon="close" :on-icon-click="handleIconClick"></el-input>
                        </el-form-item>
                        <el-form-item label="机构名称" prop="name">
                            <el-input v-model="form.name"></el-input>
                        </el-form-item>
                        <el-form-item label="唯一标识" prop="identity">
                            <el-input v-model="form.identity"></el-input>
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input
                                    type="textarea"
                                    :autosize="{ minRows: 2, maxRows: 4}"
                                    placeholder="请输入内容"
                                    v-model="form.remarks">
                            </el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import { created, updated, deleted, fetchObject, fetchTree, removeOrganizationUser} from '@/api/upms/organization'
    import {
        fetchList
    } from '@/api/upms/user'

    const sexOptions = [{label: '男', key: 1}, {label: '女', key: 2}, {label: '未知', key: 3}]
    const sortOptions = [{label: '按ID升序', key: 'id asc'}, {label: '按ID降序', key: 'id desc'}]
    const statusOptions = [{label: '正常', key: 1}, {label: '锁定', key: 2}]

    export default {
        name: 'organization',
        data() {
            return {
                loading: true,
                data: [],
                defaultProps: {
                    label: 'name',
                    children: 'children'
                },
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    create: '创建',
                    update: '编辑'
                },
                form: {
                    id: '',
                    pid: '',
                    name: '',
                    identity: '',
                    remarks: '',
                    parentName: ''
                },
                detail: {
                    id: '',
                    name: '',
                    identity: '',
                    remarks: '',
                    parentName: ''
                },

                listUser: null,
                totalUser: null,
                listLoadingUser: false,
                listQueryUser: {
                    page: 1,
                    rows: 10,
                    account: undefined,
                    realName: undefined,
                    status: undefined,
                    sex: undefined,
                    organizationId: undefined,
                    orderby: 'id asc'
                },
                multipleSelection: [],
                sexOptions,
                statusOptions,
                sortOptions,

                expandedKey: [1],
                expandedKeyEdit: [1]
            }
        },
        created() {
            this.getData()
        },
        filters: {
            sexFilter(sex) {
                const sexArray = ['男', '女', '未知']
                return sexArray[sex?--sex:'']
            },
            statusFilter(status) {
                const statusArray = ['正常', '锁定']
                return statusArray[status?--status:'']
            },
            statusTagFilter(status) {
                const statusArray = ['success', 'danger']
                return statusArray[status?--status:'']
            }
        },
        methods: {
            getData() {
                this.loading = true
                fetchTree().then(response => {
                    this.data = response.data
                    this.loading = false
                }).catch((error)=>{
                    console.log(error)
                    this.loading = false
                })
            },
            getListUser() {
                this.listLoadingUser = true
                fetchList(this.listQueryUser).then(response => {
                    this.listUser = response.data.list
                    this.totalUser = response.data.total
                    this.listLoadingUser = false
                }).catch((error)=>{
                    console.log(error)
                    this.listLoadingUser = false
                })
            },
            handleNodeClick(data, node) {
                this.listQueryUser.organizationId = data.id
                this.getListUser()

                this.detail = data
                this.detail['parentName'] = node.parent.data.name

            },
            handleSetParent(data, node) {

                var shut = false
                var sf = this.form

                //判断是否选择自己作为上级
                if(this.form.id == data.id) {
                    this.$message({
                        title: '提示', message: '选择所属上级有误',
                        type: 'info', duration: 2000
                    })
                    return
                }
                //判断选择的上级是否当前修改的上级
                res(node)
                function res(node) {
                    if(!shut) {
                        var n = node.parent
                        if(null != n) {
                            if(sf.id == n.data.id || sf.id == n.data.pid) {
                                shut = true
                            }
                            res(n)
                        }
                    }
                }
                if(shut == true) {
                    this.$message({
                        title: '提示', message: '选择所属上级有误',
                        type: 'info', duration: 2000
                    })
                    return
                }

                this.form = Object.assign({}, this.form)
                this.form['pid'] = data.id
                this.form['parentName'] = data.name
            },
            handleIconClick(ev) {
                this.form = Object.assign({}, this.form)
                this.form['pid'] = ''
                this.form['parentName'] = ''
            },
            handleCloseDialog() {
                this.resetForm()
            },
            handleReload(){
                this.getData()
            },
            handleCreate() {
                this.dialogFormVisible = true
                this.dialogStatus = 'create'
            },
            handleUpdate(data) {
                this.dialogStatus = 'update'
                fetchObject(data.id).then(response => {
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                    this.form['parentName'] = data.parentName
                    this.expandedKeyEdit = [data.id]
                })
            },
            handleDelete(data) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(data.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.detail = {}
                            this.getData()
                            this.expandedKey = [data.pid]
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getData()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                            this.expandedKey = [this.form.pid]
                        })
                    }
                })
            },
            update() {
                this.$refs['form'].validate((valid) => {
                    if(valid) {

                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })

                                this.detail = Object.assign({}, this.form)
                                this.getData()

                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                            this.expandedKey = [this.form.pid]
                        })
                    }
                })
            },
            handleSelectionChangeUser(val) {
                this.multipleSelection = val;
            },
            handleSizeChangeUser(val) {
                this.listQueryUser.rows = val
                this.getListUser()
            },
            handleCurrentChangeUser(val) {
                this.listQueryUser.page = val
                this.getListUser()
            },
            handleFilterUser() {
                this.listQueryUser.page = 1
                this.getListUser()
            },
            handleResetFilterUser() {
                this.$refs.filterFormUser.resetFields()
                this.getListUser()
            },
            handleDeleteUser(row) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    removeOrganizationUser({userOrganizationAssignId: row.userOrganizationAssignId}).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getListUser()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            resetForm() {
                this.$refs['form'].resetFields()
                this.form = {
                    id: '',
                    pid: '',
                    name: '',
                    identity: '',
                    remarks: '',
                    parentName: ''
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .tree-header{
        height: 50px;
        border-top:1px solid #d1dbe5;
        border-left:1px solid #d1dbe5;
        border-right:1px solid #d1dbe5;
        background: #eef1f6;
        span{
            display: block;
            height: 50px;
            padding-left: 5px;
            line-height: 50px;
        }
    }
    .detail-content {
        .wrapper {
            display: flex;
            justify-content: flex-start;
            margin-bottom: 10px;
            border-bottom: 1px solid #d1dbe5;
            button {
                margin-bottom: 15px;
            }
        }
        table {

        }
    }
</style>